<?php

class rewrite {

    private static $instance;
    private $rules;
    private $request_uri;
    private $uri;
    private $location;
    private $section;

    public function __construct() {
        $this->rules = $this->getRules();
        $this->request_uri = '';
        $this->uri = '';
        $this->location = '';
        $this->section = '';
        //parent::__construct() ;
    }

    public static function newInstance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function getRules() {
        //$rules=unserialize( preference::newInstance()->getPreference('rewrite_rules')); 
        // reserverd words for rules
        // item , user, contact , about, 

        $rules = array();

        // Add rule for per item
        $rules['^/songs/?$'] = 'index.php?page=songs&slug=all';
        $rules['^/songs/([0-9a-zA-Z]+)/?$'] = 'index.php?page=songs&slug=$1';
        $rules['^/artists/?$'] = 'index.php?page=artists&slug=all';
        $rules['^/artists/([0-9a-zA-Z]+)/?$'] = 'index.php?page=artists&slug=$1';
        $rules['^/categories/?$'] = 'index.php?page=categories&slug=all';
        $rules['^/categories/([0-9a-zA-Z]+)/?$'] = 'index.php?page=categories&slug=$1';

        $rules['^/search/$'] = 'index.php?page=search';

        $rules['^/user/?$'] = 'index.php?page=user&action=dashboard';
        $rules['^/user/dashboard/?'] = 'index.php?page=user&action=dashboard';
        $rules['^/user/register/?'] = 'index.php?page=user&action=register';
        $rules['^/user/sign-in/?'] = 'index.php?page=user&action=sign-in';
        $rules['^/$'] = 'index.php?page=home';
        return $rules;
    }

    public function setRules() {
        
    }

    public function listRules() {
        return $this->rules;
    }

    public function addRules($rules) {
        if (is_array($rules)) {
            foreach ($rules as $rule) {
                if (is_array($rule) && count($rule) > 1) {
                    $this->addRule($rule[0], $rule[1]);
                }
            }
        }
    }

    public function addRule($regexp, $uri) {
        $regexp = trim($regexp);
        $uri = trim($uri);
        if ($regexp != '' && $uri != '') {
            if (!in_array($regexp, $this->rules)) {
                $this->rules[$regexp] = $uri;
            }
        }
    }

    public function init() {
        // $_SERVER is not supported by Params Class... we should fix that
        if (isset($_SERVER['REQUEST_URI'])) {
            $match_found = FALSE; // default to false means its cateogry
            //define('REL_WEB_URL', '');
            //$request_uri = urldecode(preg_replace('@^' . REL_WEB_URL . '@', "", $_SERVER['REQUEST_URI']));

            $request_uri = $_SERVER['REQUEST_URI'];

            $this->extractParams($request_uri);
            $tmp_ar = explode("?", $request_uri);
            $request_uri = $tmp_ar[0];
            foreach ($this->rules as $match => $uri) {
                // UNCOMMENT TO DEBUG
                //echo 'Request URI: '.$request_uri." # Match : ".$match." # URI to go : ".$uri." <br />";
                if (preg_match('#' . $match . '#', $request_uri, $m)) {
                    $request_uri = preg_replace('#' . $match . '#', $uri, $request_uri);
                    //echo $request_uri;
                    $match_found = TRUE;
                    break;
                }
            }


            if (!$match_found) {
                $request_uri = 'index.php?page=404';
            }

            $this->extractParams($request_uri);
            $this->request_uri = $request_uri;

            if (Params::getParam('page') != '') {
                $this->location = Params::getParam('page');
            };
            if (Params::getParam('action') != '') {
                $this->section = Params::getParam('action');
            };
        }
    }

    public function extractURL($uri = '') {
        $uri_array = explode('?', str_replace('index.php', '', $uri));
        if (substr($uri_array[0], 0, 1) == "/") {
            return substr($uri_array[0], 1);
        } else {
            return $uri_array[0];
        }
    }

    public function extractParams($uri = '') {
        $uri_array = explode('?', $uri);
        $url = substr($uri_array[0], 1);
        $length_i = count($uri_array);
        for ($var_i = 1; $var_i < $length_i; $var_i++) {
            if (preg_match_all('|&([^=]+)=([^&]*)|', '&' . $uri_array[$var_i] . '&', $matches)) {
                $length = count($matches[1]);
                for ($var_k = 0; $var_k < $length; $var_k++) {
                    Params::setParam($matches[1][$var_k], $matches[2][$var_k]);
                }
            }
        }
    }

    public function removeRule($regexp) {
        unset($this->rules[$regexp]);
    }

    public function clearRules() {
        unset($this->rules);
        $this->rules = array();
    }

    public function get_request_uri() {
        return $this->request_uri;
    }

    public function set_location($location) {
        $this->location = $location;
    }

    public function get_location() {
        return $this->location;
    }

    public function get_section() {
        return $this->section;
    }

}
